package com.my.xadmin.security.service.impl;

import com.my.framework.base.service.impl.BaseServiceImpl;
import com.my.framework.exception.ServiceException;
import com.my.framework.page.Page;
import com.my.framework.page.PageUtils;
import com.my.framework.shiro.ShiroDbRealm;
import com.my.framework.shiro.ShiroUser;
import com.my.xadmin.security.entity.Organization;
import com.my.xadmin.security.repository.OrganizationDAO;
import com.my.xadmin.security.repository.UserDAO;
import com.my.xadmin.security.service.OrganizationService;
import com.my.xadmin.security.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.validation.Validator;
import java.io.InputStream;
import java.util.*;
import java.util.Map.Entry;

@Service
@Transactional
public class OrganizationServiceImpl extends BaseServiceImpl<Organization, Long> implements OrganizationService
{
    private final static Logger LOGGER = LoggerFactory.getLogger(OrganizationServiceImpl.class);
    @Autowired
    public OrganizationServiceImpl(OrganizationDAO organizationDAO)
    {
        super(organizationDAO);
        this.organizationDAO = organizationDAO;
        //codeNotes = new CodeNotes("PT");
    }
//    // 自编码生成器
//    /** The generate coder. */
//    @Autowired
//    private GenerateCoder generateCoder;
//    /** The code notes. */
//    private CodeNotes codeNotes;// 自编码生成规则

    @Autowired
    private UserDAO userDAO;

    @Autowired
    private ShiroDbRealm shiroRealm;

    @Autowired
    private OrganizationDAO organizationDAO;

    @Autowired
    private UserService userService;

    @Override
    public void save(Organization organization)
    {
        organizationDAO.save(organization);
    }
    
    @Override
    public Organization get(Long id)
    {
        return organizationDAO.findOne(id);
    }
    
    @Override
    public void update(Organization organization)
    {
        organizationDAO.save(organization);
    }
    
    @Autowired
    private Validator validator;

    @PersistenceContext
    private EntityManager em;
    
    /**
     * @param id
     */
    public void delete(Long id)
        throws ServiceException
    {
        if (isRoot(id))
        {
            throw new ServiceException("不允许删除根组织。");
        }

        Organization organization = this.get(id);

        // 先判断是否存在子模块，如果存在子模块，则不允许删除
        if (organization.getChildren().size() > 0)
        {
            throw new ServiceException(organization.getName() + "组织下存在子组织，不允许删除。");
        }

        if (userDAO.findByOrganizationId(id).size() > 0)
        {
            throw new ServiceException(organization.getName() + "组织下存在用户，不允许删除。");
        }

        organizationDAO.delete(organization);
    }

    /**
     * @param parentId
     * @param page
     * @return
     */
    public List<Organization> find(Long parentId, Page page)
    {
        org.springframework.data.domain.Page<Organization> springDataPage =
            organizationDAO.findByParentId(parentId, PageUtils.createPageable(page));
        page.setTotalCount(springDataPage.getTotalElements());
        return springDataPage.getContent();
    }

    /**
     * @param parentId
     * @param name
     * @param page
     * @return
     */
    public List<Organization> find(Long parentId, String name, Page page)
    {
        org.springframework.data.domain.Page<Organization> springDataPage =
            organizationDAO.findByParentIdAndNameContaining(parentId, name, PageUtils.createPageable(page));
        page.setTotalCount(springDataPage.getTotalElements());
        return springDataPage.getContent();
    }
    
    /**
     * 判断是否是根组织.
     */
    private boolean isRoot(Long id)
    {
        Organization org = organizationDAO.findOne(id);
        if (null != org)
        {
            return org.getIsRoot();
        }
        throw new ServiceException("组织不存在!");
    }
    
    /**
     * 
     * @return
     */
    public Organization getTree()
    {
        List<Organization> list = organizationDAO.findAllWithCache();
        
        List<Organization> rootList = makeTree(list);
        
        return rootList.get(0);
    }
    
    public List<Organization> makeTree(List<Organization> list)
    {
        List<Organization> parent = new ArrayList<Organization>();
        // get parentId = null;
        for (Organization e : list)
        {
            if (e.getParent() == null)
            {
                e.setChildren(new ArrayList<Organization>(0));
                parent.add(e);
            }
        }
        // 删除parentId = null;
        list.removeAll(parent);
        
        makeChildren(parent, list);
        
        return parent;
    }
    
    private void makeChildren(List<Organization> parent, List<Organization> children)
    {
        if (children.isEmpty())
        {
            return;
        }
        
        List<Organization> tmp = new ArrayList<Organization>();
        for (Organization c1 : parent)
        {
            for (Organization c2 : children)
            {
                c2.setChildren(new ArrayList<Organization>(0));
                if (c1.getId().equals(c2.getParent().getId()))
                {
                    c1.getChildren().add(c2);
                    tmp.add(c2);
                }
            }
        }
        
        children.removeAll(tmp);
        
        makeChildren(tmp, children);
    }
    
    @Override
    public Organization findByCode(String orgCode)
    {
        return organizationDAO.findByCode(orgCode);
    }
    

    @Override
    public List<Organization> findByParentId(Long parentId)
    {
        return organizationDAO.findByParentId(parentId);
    }
    
    @Override
    public List<Organization> findAll()
    {
        
        return organizationDAO.findAll();
    }
    
    @Override
    public List<Organization> findByAreaCode(String areaCode)
    {
        return organizationDAO.findByAreaCode(areaCode);
    }
    
    @Override
    public Organization findByAreaCodeAndJglx(String areaCode, String jglx)
    {
        return organizationDAO.findByAreaCodeAndJglx(areaCode, jglx);
    }
    
    @Override
    public boolean isLocal(String orgCode)
    {
        Organization organization = null;
        organization = organizationDAO.findByCode(orgCode);
        if (organization==null){
            return false;
        }
        return true;
    }
    
    @Override
    public String getCityCode(String areaCode)
    {
        if (StringUtils.isNotBlank(areaCode) && areaCode.length() == 6)
        {
            return StringUtils.substring(areaCode, 0, 4) + "00";
        }
        return null;
    }
    
    @Override
    public List<Organization> findByTbbzAndIsRoot(String tbbz, Boolean flag)
    {
        return organizationDAO.findByTbbzAndIsRoot(tbbz, flag);
    }
    
    @Override
    public Organization findByAreaCodeAndJglx(String areaCode, String jglx, String code)
    {
        return organizationDAO.findByAreaCodeAndJglxAndCode(areaCode, jglx,code);
    }

	@Override
	public Organization makeCode(Organization organization, String param) {
		String zcode = null;
        if (StringUtils.isBlank(organization.getPtzbm()))
        {
            //zcode = generateCoder.getNextCode(codeNotes, null);// 平台自编码先使用默认规则
            organization.setPtzbm(zcode);
        }
        return organization;
	}

	@Override
	public Organization getTreeByOrg(Organization org) {
        Organization org2 = organizationDAO.findByCode(org.getCode());
        List<Organization> allList = new ArrayList<Organization>();
        allList.add(org2);
        getChildPort(org2,allList);
        
        List<Organization> parent = new ArrayList<Organization>();
        for (Organization e : allList)
        {
            if (e.getCode().equals(org2.getCode()) )
            {
                e.setChildren(new ArrayList<Organization>(0));
                parent.add(e);
            }
        }
        // 删除parentId = null;
        allList.removeAll(parent);
        
        makeChildren(parent, allList);
        
        return parent.get(0);
        }

    /***
     * 递归调用
     * @param orgniz
     * @see [类、类#方法、类#成员]
     */
    public void getChildPort(Organization orgniz,List<Organization> allList){
        //获取子节点
        List<Organization> child = organizationDAO.findByParentId(orgniz.getId());
        //找到子节点的子节点
        if(child != null && child.size()>0){
            //将子节点添加到父加节点
            for(Organization o : child){
                o.setChildren(new ArrayList<Organization>());
                allList.add(o);
                //递归调用
                getChildPort(o,allList);
            }
        }
    }

}
